# -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 16:28:35 2021

@author: 98330
"""
import json
 
def save_data_switch(file_path, file_name, data):
    f = open(file_path + file_name, "w")
    s = str(data).replace('[','').replace(']','')
    s = s.replace("'",'').replace(',','|').replace(' ', '') +'\n' 
    f.write(s)
    f.close()
    f = open(file_path + file_name, "a")
    return f

def save_data(file_path, file_name, data):
    f = open(file_path + file_name, "w")
    s = str(data).replace('[','').replace(']','')
    s = s.replace("'",'').replace(',','|').replace(' ', '') +'\n' 
    f.write(s)
    f.close()

def save_json(file_path, file_name, data):
    f = open(file_path + file_name, "w")
    data_json = json.dumps(data)
    json.dump(data_json,f)
    f.close()

def load_json(file_path, file_name):
    f = open(file_path + file_name, "r") 
    data_json = json.load(f)
    data = json.loads(data_json)
    return data
    
def add_data(file_path, file_name, data):
    f = open(file_path + file_name, "a")
    s = str(data).replace('[','').replace(']','')
    s = s.replace("'",'').replace(',','|').replace(' ', '') +'\n'  
    f.write(s)
    f.close()
    
def add_data_switch(f, data, state):
    s = str(data).replace('[','').replace(']','')
    s = s.replace("'",'').replace(',','|').replace(' ', '') +'\n'  
    f.write(s)
    if state == 1:
        f.close()
        
def save_list_2D(file_path, file_name, list_2D):
    f = save_data_switch(file_path, file_name, list_2D[0])
    for i in range(1, len(list_2D) - 1):
        add_data_switch(f, list_2D[i], 0)
    add_data_switch(f, list_2D[len(list_2D) - 1], 1)

def list_to_2D(lanti, long, frequ, y_list, path, file):
    data_sum = []
    for j in range(len(lanti)):
        data_temp = []
        data_temp.append(lanti[j])
        data_temp.append(long[j])
        data_temp.append(frequ[j])
        data_temp.append(y_list[j])
        data_sum.append(data_temp) 
    save_list_2D(path, file, data_sum)

def load_data(file_path, file_name):
    f = open(file_path + file_name, "r")
    arr = []
    line = f.readline()
    while line:
        list_line = line.split("|")
        arr.append(list_line)
        line = f.readline()
    f.close()
    print("文件读取成功")
    return arr

def load_data_float(file_path, file_name):
    f = open(file_path + file_name, "r")
    arr = []
    line = f.readline()
    while line:
        list_line = line.split("|")
        list_line = list(map(float,list_line))
        arr.append(list_line)
        line = f.readline()
    f.close()
    print("文件读取成功")
    return arr

def array_to_list(array):
    list_2D = []
    for i in range(len(array)):
        list_2D.append(list(array[i,:]))
    return list_2D
        
    
